﻿using System;
using System.Collections.Generic;

namespace YummyGame.Framework
{
    public class SkillAction_delay:SkillAction
    {
        private Expression time;
        private SkillAction delayAction;

        private float _t;
        private bool _isRun;
        private ActionRunState _targetExcuteState;


        public override void Reactive()
        {
            delayAction = null;
            _t = 0;
            _isRun = false;
            _targetExcuteState = ActionRunState.Running;

            SkillActionPrototype_delay delay = Prototype as SkillActionPrototype_delay;
            time = ParseRuntimeExpression(delay.time);
            delayAction = delay.delayAction?.ToRuntime(Executer);
        }

        public override ActionRunState Excute()
        {
            if (delayAction == null) return ActionRunState.Success;
            _t = time.Calculate();
            if (_t < 0)
            {
                _isRun = true;
                return delayAction.Excute();
            }
            new DelayTask(_t,Executer.taskLooper).OnTaskFinish((_) =>
            {
                _isRun = true;
                _targetExcuteState = delayAction.Excute();
            });
            return ActionRunState.Running;
        }

        public override ActionRunState Run()
        {
            if (!_isRun) return ActionRunState.Running;
            if (_targetExcuteState == ActionRunState.Success || _targetExcuteState == ActionRunState.Failure) return _targetExcuteState;
            return delayAction.Run();
        }

        public override void Dispose()
        {
            Pools.GetSkillRuntime<SkillAction_delay>().Recover(this);
        }
    }
}
